#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2021/6/8
# @Author    :zhangxuchuo
# @Email     :zhangxuchuo@bbdservice.com
# @File      :IC34_6MonsSmalLoanCnt
# @Software  :PyCharm


'''eof
name:近6个月发放的小额贷款笔数（小额贷款公司）
code:IC34_6MonsSmalLoanCnt
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime
import pandas as pd

# reload(sys)
# sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--', []]


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
    '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

# Factor=count（借贷账户信息（PDA）/借贷账户信息单元（PD01）/基本信息段（PD01A）/业务种类(PD01AD03)为“51”且开立日期(PD01AR01)在6个月之内的数据）

def IC34_6MonsSmalLoanCnt():
    account_list = []
    data = IC_DSJ_2D.get('data')
    PDA = getTable(data, 'PDA', 1, 0)
    #PDA 借贷账户信息 [1..1]
    if PDA == [{}]:
        return '缺失值'
    elif PDA == 0:
        return 0
    else:
        #PD01 借贷账户信息单元 [0..*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return '缺失值'
        elif PD01 == 0:
            return 0
        else:
            for i in PD01:
                #PD01A 基本信息段 [1..1]
                PD01A = getTable(i, 'PD01A', 1, 1)
                if PD01A == [{}]:
                    return '缺失值'
                elif PD01A == 0:
                    return 0
                else:
                    # PD01AD03 业务种类 [0..1]
                    # PD01AR01 开立日期 [1..1]
                    PD01AD03 = PD01A[0].get('PD01AD03')
                    PD01AR01 = PD01A[0].get('PD01AR01')
                    PD01AR01 = Formate(PD01AR01)
                    if PD01AD03 not in null_type_list and PD01AR01 not in null_type_list:
                        if PD01AD03 == '51' and (int((datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=6)).strftime("%Y%m%d")) <= int(PD01AR01) <= int(datetime.datetime.now().strftime('%Y%m%d'))):
                            account_list.append(1)
                        else:
                            account_list.append(0)
                    else:
                        account_list.append('缺失值')

    if len(list(set(account_list))) == 1 and list(set(account_list))[0] == '缺失值':
        return '缺失值'
    elif len(list(set([i for i in account_list if i != '缺失值']))) == 1 and list(set([i for i in account_list if i != '缺失值']))[0] == 0:
        return 0
    else:
        res = [i for i in account_list if i != '缺失值' and i != 0]
        return sum(res)

result = IC34_6MonsSmalLoanCnt()
# if __name__ == '__main__':
#     with open(r'C:\Users\john\Desktop\samples\IC_DSJ_2D.json',encoding='utf8') as ff:
#         dd = json.loads(ff.read())
#     IC_DSJ_2D = dd['IC_DSJ']
#     result = IC34_6MonsSmalLoanCnt()
#     print(result)